/**
 * 文件名:IndexController.java
 * 版本信息:1.0
 * 日期:2015-5-17
 * Copyright 广州点步信息科技
 * 版权所有
 */
package com.dbumama.market.web.mobile.index.controller;

import java.util.Date;
import java.util.List;

import com.dbumama.market.model.*;
import com.dbumama.market.service.api.order.OrderService;
import com.dbumama.market.service.api.user.UserService;
import com.dbumama.market.service.constants.Constants;
import com.dbumama.market.web.core.utils.SMSUtils;
import com.dbumama.market.web.core.utils.StringUtils;
import com.jfinal.kit.HashKit;

import com.dbumama.market.service.api.product.ProductCategoryService;
import com.dbumama.market.service.api.product.ProductMobileParamDto;
import com.dbumama.market.service.api.product.ProductMobileResultDto;
import com.dbumama.market.service.api.product.ProductService;
import com.dbumama.market.service.api.shop.ShopService;
import com.dbumama.market.service.api.user.PhoneCodeService;
import com.dbumama.market.service.api.user.UserException;
import com.dbumama.market.service.api.weipage.WeiPageService;
import com.dbumama.market.web.core.annotation.RouteBind;
import com.dbumama.market.web.core.controller.BaseMobileController;
import com.dbumama.market.web.core.plugin.spring.Inject.BY_NAME;
import com.dbumama.market.web.core.utils.IpKit;
import com.jfinal.aop.Clear;

import cn.dreampie.captcha.CaptchaRender;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.ehcache.CacheKit;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

/**
 * @author: wjun.java@gmail.com
 * @date:2015-5-17
 */
@RouteBind(path="/")
public class IndexController extends BaseMobileController{

	@BY_NAME
	private PhoneCodeService phoneCodeService;
	@BY_NAME
	private ProductService productService;
	@BY_NAME
	private ProductCategoryService productCategoryService;
	@BY_NAME
	private ShopService shopService;
	@BY_NAME
	private WeiPageService weiPageService;
	@BY_NAME
	private UserService userService;
	@BY_NAME
	private OrderService orderService;
	
	public void index(){
		//查询卖家创建的活动列表 在有效时间范围内可见的 并且是没有删除的活动 并且是进行中的活动
		Shop shop = shopService.findBySeller();
		setAttr("shop", shop);
		
		ProductMobileParamDto mobileParamDto = new ProductMobileParamDto(getSellerId(), getPageNo());
		//查询商品列表
		List<ProductMobileResultDto> indexProducts = productService.getIndexProduct(mobileParamDto);
		setAttr("indexProducts", indexProducts);
		List<ProductMobileResultDto> hotProducts = productService.getHotProduct(mobileParamDto);
		setAttr("hotProducts", hotProducts);
		List<ProductMobileResultDto> newProducts = productService.getNewProduct(mobileParamDto);
		setAttr("newProducts", newProducts);
		List<ProductMobileResultDto> commondProducts = productService.getRecommendProduct(mobileParamDto);
		setAttr("commondProducts", commondProducts);
		
		/*WeiPage entity=weiPageService.findByStatus(getSellerId(), 1);
		if(entity!=null){
			setAttr("entity", entity);
			setAttr("url", "feature/show?id="+entity.getId());
			render("/feature/index.html");
		}*/
	}
	
	public void forbid(){}
	public void error(){}
	public void auth(){setAttr("rUrl", getPara("rUrl"));}
	
	public void sendCode(){
		final String phone = getPara("phone");
		if(StringUtils.isEmpty(phone)){
			rendFailedJson("手机号码为空");
			return;
		}
		try {
			rendSuccessJson(phoneCodeService.getCodeByAgent(phone, IpKit.getRealIp(getRequest())));
		} catch (UserException e) {
			rendFailedJson(e.getMessage());
		} 
	}
	
	public void search(){
		List<ProductCategory> productCategorys = productCategoryService.list();
		/*List<ProductCategory> validCategorys = new ArrayList<ProductCategory>();
		for(ProductCategory pcate : productCategorys){
			List<Product> products = productService.find("select * from " + Product.table + " where product_category_id=? ", pcate.getId());
			if(products != null && products.size()>0){
				validCategorys.add(pcate);
			}
		}*/
		setAttr("productCategory", productCategorys);
		render("/search/search.html");
	}

	@Clear
    public void captcha() {
        int width = 0, height = 0, minnum = 0, maxnum = 0, fontsize = 0;
        CaptchaRender captcha = new CaptchaRender();
        if (isParaExists("width")) {
            width = getParaToInt("width");
        }
        if (isParaExists("height")) {
            height = getParaToInt("height");
        }
        if (width > 0 && height > 0)
            captcha.setImgSize(width, height);
        if (isParaExists("minnum")) {
            minnum = getParaToInt("minnum");
        }
        if (isParaExists("maxnum")) {
            maxnum = getParaToInt("maxnum");
        }
        if (minnum > 0 && maxnum > 0)
            captcha.setFontNum(minnum, maxnum);
        if (isParaExists("fontsize")) {
            fontsize = getParaToInt("fontsize");
        }
        if (fontsize > 0)
            captcha.setFontSize(fontsize, fontsize);
        // 干扰线数量 默认0
        captcha.setLineNum(1);
        // 噪点数量 默认50
        captcha.setArtifactNum(10);
        // 使用字符 去掉0和o 避免难以确认
        captcha.setCode("123456789");
        //验证码在session里的名字 默认 captcha,创建时间为：名字_time
        // captcha.setCaptchaName("captcha");
        //验证码颜色 默认黑色
        // captcha.setDrawColor(new Color(255,0,0));
        //背景干扰物颜色  默认灰
        // captcha.setDrawBgColor(new Color(0,0,0));
        //背景色+透明度 前三位数字是rgb色，第四个数字是透明度  默认透明
        // captcha.setBgColor(new Color(225, 225, 0, 100));
        //滤镜特效 默认随机特效 //曲面Curves //大理石纹Marble //弯折Double //颤动Wobble //扩散Diffuse
        captcha.setFilter(CaptchaRender.FilterFactory.Curves);
        // 随机色 默认黑验证码 灰背景元素
        captcha.setRandomColor(true);
        render(captcha);
    }

	public void login(){
		render("login.html");
	}

	public void doLogin(){
	    try{
            final String phone = getPara("phone");
            final String password = getPara("password");
            BuyerUser user = userService.findUser(phone, HashKit.md5(password));
            //验证账户密码
            if(user == null){
				renderJson(Ret.fail("msg","用户名或密码错误！"));
                return;
            }
            //session存储用户信息
            setSessionAttr(Constants.BUYER_USER_IN_SESSION,user);

            //更新登陆用户信息
            user.setLastLoginTime(new Date());
            user.setAccessIp(IpKit.getRealIp(getRequest()));
            boolean flag = user.update();
            log.info("----------------------update login_message result:["+flag+"]------------------------------");
            renderJson(Ret.ok());
        }catch (Exception e){
            log.error(e);
			renderJson(Ret.fail("msg","系统繁忙，请稍候再试！"));
            return;
        }
	}

	public void register(){
		render("register.html");
	}

	public void smsAjax(){
		String phone = getPara("phone");
		String type = getPara("type");
		String code = "123456";
//		String code = SMSUtils.sendSMSCode(phone,Integer.parseInt(type));
		if(code == null){
			renderJson(Ret.fail("msg", "短信验证码发送失败"));
			return;
		}
		//保存发送短信记录
		SmsCode smsCode = new SmsCode();
		smsCode.setPhone(phone);
		smsCode.setCode(code);
		smsCode.setType(type);
		smsCode.setCreated(new Date());
		smsCode.setUpdated(new Date());
		boolean flag = smsCode.save();
		log.info("-----------------------save sms_code result:["+flag+"]----------------------------");
		CacheKit.put("tenMinute", phone, code);
		renderJson(Ret.ok());
    }

	public void doRegister(){
		try {
			String phone = getPara("phone");
			log.info("--------------------phone:["+phone+"] register_start---------------------");
			String password = getPara("password");
			String code = getPara("code");
			String recPhone = getPara("recPhone");
			BuyerUser user = userService.findByTel(phone);
			if(user != null){
				log.debug("check mobile["+phone+"] already exist");
				renderJson(Ret.fail("msg", "该手机号已被注册"));
				return;
			}
			if (!code.equals(CacheKit.get("tenMinute", phone))) {
				log.debug("check mobile["+phone+"] code is not correct");
				renderJson(Ret.fail("msg", "验证码错误"));
				return;
			}

			//判断推荐账号是否符合条件
			String rec_buyerId = "";
			if(!StringUtils.isEmpty(recPhone)){
				BuyerUser buyerUser = userService.findByTel(recPhone);
				if(buyerUser==null){
					log.debug("check buyer_id["+recPhone+"] is null");
					renderJson(Ret.fail("msg", "推荐用户不存在"));
					return;
				}else{
					rec_buyerId = buyerUser.getId().toString();
				}
			}

			BuyerUser buyerUser = new BuyerUser();
			buyerUser.setAccessIp(IpKit.getRealIp(getRequest()));
			buyerUser.setPhone(phone);
			buyerUser.setPassword(HashKit.md5(password));
			buyerUser.setCreated(new Date());
			buyerUser.setSellerId(Long.parseLong("1"));
			buyerUser.setStatus("0");
			buyerUser.setLevelId("0");
			boolean flag = buyerUser.save();
			log.info("-------------------------save buyerUser result:["+flag+"]------------------------------");

			BuyerUser buyerUser1 = userService.findByTel(phone);

			BuyerExtend buyerExtend = new BuyerExtend();
			buyerExtend.setBuyerId(buyerUser1.getId());
			if(StringUtils.isEmpty(rec_buyerId)){
				buyerExtend.setRefBuyerId("");
				buyerExtend.setParentIds("");
			}else{
				BuyerExtend recExtend = userService.findExtend(Long.parseLong(rec_buyerId));
				buyerExtend.setRefBuyerId(rec_buyerId);
				buyerExtend.setParentIds(recExtend.getParentIds() + recExtend.getBuyerId() + ",");
			}

			buyerExtend.setCreated(new Date());
			buyerExtend.setUpdated(new Date());
			flag =buyerExtend.save();
			log.info("--------------------phone:["+phone+"] save buyerExtend result:["+flag+"]----------------------");

			if(flag){
				renderJson(Ret.ok());
			}else{
				renderJson(Ret.fail("msg", "注册失败！"));
			}
			log.info("--------------------phone:["+phone+"] register_end----------------------");
		}catch (Exception e){
			log.error("doRegister error",e);
			renderJson(Ret.fail("msg", "系统繁忙，请稍候再试！"));
		}
    }

    public String getParentId(String parentId){
		if(StringUtils.isEmpty(parentId)){
			parentId="";
		}
		return parentId;
	}

    public void forget(){
		render("forget.html");
	}

	public void resetPwd(){
    	try{
			String phone = getPara("phone");
			log.info("--------------------phone:["+phone+"] resetPwd_start---------------------");
			String password = getPara("password");
			String code = getPara("code");
			BuyerUser user = userService.findByTel(phone);
			if(user == null){
				log.debug("check mobile["+phone+"] already exist");
				renderJson(Ret.fail("msg", "用户不存在"));
				return;
			}
			if (!code.equals(CacheKit.get("tenMinute", phone))) {
				log.debug("check mobile["+phone+"] code is not correct");
				renderJson(Ret.fail("msg", "验证码错误"));
				return;
			}
			user.setPassword(HashKit.md5(password));
			user.setUpdated(new Date());
			boolean flag = user.update();
			if(flag){
				renderJson(Ret.ok());
			}else{
				renderJson(Ret.fail("msg", "系统繁忙，请稍候再试！"));
			}
		}catch (Exception e){
			log.error(e);
			renderJson(Ret.fail("msg", "系统繁忙，请稍候再试！"));
		}

	}

	public void payCenter(){
		render("/verified/payCenter.html");
	}

	public void toShare(){
		setAttr("phone",getBuyerUser().getPhone());
		render("/agent/share.html");
	}

	public void toRegist(){
		String recPhone = getPara("recPhone");
		setAttr("recPhone",recPhone);
		render("codeRegister.html");
	}

	public void logout(){
		Subject currentUser = SecurityUtils.getSubject();
		if (SecurityUtils.getSubject().getSession() != null) {
			currentUser.logout();
		}
		redirect("/");
	}
}
